/**
 *  @Author DongYan-[7632632@qq.com]
 */
var client = {
    debug:false,
    server: {
        init: function (srcHttp) {
            this.http = srcHttp;
        },
        host: function () {//[debug] from nodeJs server api
            return "http://localhost:29153/";
            //return "http://localhost:8000/";
            //return "http://192.168.1.123:19644/api";
        },
        get: function (api, params, successFn, errorFn, isTimer, time) {
            if(client.debug)
                return;
            
            var url = this.host() + '/' + api;
            var get = function () {
                $.ajax({
                    type: "GET",
                    url: url,
                    dataType: "json",
                    data: params,
                    traditional: true,
                })
                    .done(function (data, textStatus, jqXHR) {
                        successFn(data, textStatus, jqXHR);
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        errorFn(jqXHR, textStatus, errorThrown);
                    });
            };
             if (isTimer) {
                 client.tool.timer(get, time);
             } else {
                 get();
             }
        },
        post: function (api, params, successFn, errorFn, isTimer, time) {
            var url = this.host() + '/' + api;
            var post = function () {
                $.ajax({
                    type: "POST",
                    url: url,
                    dataType: "json",
                    data: JSON.stringify(params),
                    traditional: true,
                })
                    .done(function (data, textStatus, jqXHR) {
                        successFn(data, textStatus, jqXHR);
                    })
                    .fail(function (jqXHR, textStatus, errorThrown) {
                        errorFn(jqXHR, textStatus, errorThrown);
                    });
            };
            if (isTimer) {
                client.tool.timer(post, time);
            } else {
                post();
            }
        },
        getResult: function (data) {
            this.result.code = data.reCode;
            this.result.data = data.reData;
            this.result.msg = data.reMsg;
            return this.result;
        },
        result: {},
    },
    api: {
        //重置密码
        resetPassword: function (paramsobj, done, fail) {
            client.server.get('/BackStage/ResetPassword', paramsobj, done, fail, false);
        },
        //更新用户信息
        modifyUser: function (paramsobj, done, fail) {
            client.server.get('/BackStage/ModifyUser', paramsobj, done, fail, false);
        },
        //检查MMSI是否正确
        checkMMSI: function (paramsobj,done, fail) {
            client.server.get('/BackStage/ValidateMMSI', paramsobj, done, fail, false);
        },

        //获取单个版本库
        getVersionLib: function (paramsobj, done, fail) {
            client.server.get('/BackStage/GetVersionLib', paramsobj, done, fail, false);
        },
        //获取单个版本库
        updateVersionLib: function (paramsobj, done, fail) {
            client.server.get('/BackStage/UpdateVersionLib', paramsobj, done, fail, false);
        },
        //添加版本库
        addVersionLib: function (paramsobj, done, fail) {
            client.server.get('/BackStage/UpdateVersionLib', paramsobj, done, fail, false);
        },

        //设置公司下所有船舶有效时间
        setCompanyExpirationDate: function (paramsobj, done, fail) {
            client.server.get('/BackStage/SetCompanyExpirationDate', paramsobj, done, fail, false);
        },
        //设置用户船舶有效时间
        setUserExpirationDate: function (paramsobj, done, fail) {
            client.server.get('/BackStage/setUserExpirationDate', paramsobj, done, fail, false);
        },


        //读取配置文件
        readConfig: function (paramsobj, done, fail) {
            client.server.get('/BackStage/ReadConfig', paramsobj, done, fail, false);
        },
        //添加配置文件
        addConfig: function (paramsobj, done, fail) {
            client.server.get('/BackStage/AddConfig', paramsobj, done, fail, false);
        },
        //更新配置文件
        modifConfigs: function (paramsobj, done, fail) {
            client.server.get('/BackStage/ModifConfigs', paramsobj, done, fail, false);
        },
        //删除配置文件
        deleteConfig: function (paramsobj, done, fail) {
            client.server.get('/BackStage/DeleteConfigs', paramsobj, done, fail, false);
        },
        //下载配置文件
        downloadConfig: function (paramsobj, done, fail) {
            client.server.get('/BackStage/DownloadConfig', paramsobj, done, fail, false);
        },
        

        //更新图片信息
        modifyImage: function (paramsobj, done, fail) {
            client.server.get('/BackStage/ModifyImage', paramsobj, done, fail, false);
        },
        //更新图片信息
        deleteImage: function (paramsobj, done, fail) {
            client.server.get('/BackStage/DeleteImage', paramsobj, done, fail, false);
        },
        //下载图片
        downloadImage: function (paramsobj, done, fail) {
            client.server.get('/BackStage/DownloadImages', paramsobj, done, fail, false);
        },
        

    },
    data: {
        setCache: function (key, data) {
            if (typeof(Storage) !== "undefined") {
                localStorage.setItem(key, JSON.stringify(data));
            } else {
                client.tool.log('your BOW is not supp!');
            }
        },
        getCache: function (key, loadingFn, callback) {
            if (typeof(Storage) !== "undefined") {
                var cacheData = localStorage.getItem(key);
                if (cacheData !== null) {
                    callback(JSON.parse(cacheData));
                } else {
                    loadingFn().then(function (data) {
                        client.data.setCache(key, data);
                        callback(data);
                    });
                }
            } else {
                client.tool.log('your BOW is not supp!');
            }
        },
        filter: function (source, equalFn) {
            var currentArr = [];
            for (var index in source) {
                var model = source[index];
                if (equalFn(model)) {
                    currentArr.push(model);
                }
            }
            return currentArr;
        }
    },
    tool: {
        log: function (msg) {
            console.log(msg);
        },
        mergeObject: function (orginal, newObject) {
            for (var attr in newObject) {
                orginal[attr] = newObject[attr];
            }
            return orginal;
        },
        timer: function (fn, time) {
            setInterval(fn, time);
        },
        weekNumOfYear: function (year, month, day) {/*开始日期:周四 结束日期:周五*/
            client.tool.log(year);
            client.tool.log(month);
            client.tool.log(day);
            var beginDay = new Date(year, 0, 1);
            var weekDay = beginDay.getDay();
            if (weekDay === 6)
                beginDay = new Date(year, 0, 7);
            else
                beginDay = new Date(year, 0, 6 - weekDay);

            var today = new Date(year, parseInt(month) - 1, day);
            var weekNum = Math.ceil((today - beginDay) / 86400000 / 7);
            if (today.getDay() === 5) {
                weekNum = weekNum + 1;
            }
            return weekNum;
        }
    },
    component: {
        loading: {
            open: function () {
                document.getElementById("loading").classList.remove("loading-hide");
                document.getElementById("loading").classList.add("loading");
            },
            close: function () {
                document.getElementById("loading").classList.remove("loading");
                document.getElementById("loading").classList.add("loading-hide");
            }
        }
    },
    page: {
        currentPageNo: 1,
        pageCount: 10,
        prevPage: function () {
            var pageNo = this.currentPageNo - 1;
            if (pageNo !== 0) {
                this.currentPageNo = pageNo;
            }
        },
        nextPage: function () {
            this.currentPageNo = this.currentPageNo + 1;
        },
        paging: function (srcArray, pageCount, pageNo) {
            //change the page content
            var changePage = function (src, count, no) {
                var currentArray = [];
                if (src !== undefined && srcArray.length !== 0) {
                    var startItemIndex = (no - 1) * count;
                    return src.slice(startItemIndex, startItemIndex + count);
                }
                return currentArray;
            };
            return changePage(srcArray, pageCount, pageNo);
        }
    },
    file: {
        reader: new FileReader(),
        readAsText: function (file, loadCompleteFn) {
            this.reader.readAsText(file);
            this.reader.onload = function () {
                var result = toResult(this.result);
                loadCompleteFn(result);
            };
            function toResult(result) {
                var arr = result.split('\n');
                var jsonArr = [];
                for (var i = 1; i < arr.length; i++) {
                    if (arr[i] !== "") {
                        var columns = arr[i].split('\t');
                        var obj = {};
                        for (var j = 0; j < columns.length; j++) {
                            obj[j] = columns[j];
                        }
                        jsonArr.push(obj);
                    }
                }
                return jsonArr;
            };
        },
    },
    cookie: 
        {
            getCookie:function(name)
            {
                var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
                if (arr = document.cookie.match(reg))
                    return unescape(arr[2]);
                else
                    return null;
            },
            delCookie:function(name)
            {
                var exp = new Date();
                exp.setTime(exp.getTime() - 1);
                var cval = this.getCookie(name);
                if (cval != null)
                    document.cookie = name + "=" + cval + ";expires=" + exp.toGMTString();
            }
        },


    XML: {
        reader: new FileReader(),
        loadxml: function (xmlString) {
            var xmlDoc = null;
            //判断浏览器的类型
            //支持IE浏览器 
            if (!window.DOMParser && window.ActiveXObject) {   //window.DOMParser 判断是否是非ie浏览器
                var xmlDomVersions = ['MSXML.2.DOMDocument.6.0', 'MSXML.2.DOMDocument.3.0', 'Microsoft.XMLDOM'];
                for (var i = 0; i < xmlDomVersions.length; i++) {
                    try {
                        xmlDoc = new ActiveXObject(xmlDomVersions[i]);
                        xmlDoc.async = false;
                        xmlDoc.loadXML(xmlString); //loadXML方法载入xml字符串
                        break;
                    } catch (e) {
                    }
                }
            }
                //支持Mozilla浏览器
            else if (window.DOMParser && document.implementation && document.implementation.createDocument) {
                try {
                    /* DOMParser 对象解析 XML 文本并返回一个 XML Document 对象。
                     * 要使用 DOMParser，使用不带参数的构造函数来实例化它，然后调用其 parseFromString() 方法
                     * parseFromString(text, contentType) 参数text:要解析的 XML 标记 参数contentType文本的内容类型
                     * 可能是 "text/xml" 、"application/xml" 或 "application/xhtml+xml" 中的一个。注意，不支持 "text/html"。
                     */
                    domParser = new DOMParser();
                    xmlDoc = domParser.parseFromString(xmlString, 'text/xml');
                } catch (e) {
                }
            }
            else {
                return null;
            }

            return xmlDoc;
        }
    }
};

//获取get参数
var GetQueryString = function (name) {
    var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
    var r = window.location.search.substr(1).match(reg);
    if (r != null) return unescape(r[2]); return null;
}

// (new Date()).Format("yyyy-MM-dd hh:mm:ss.S") ==> 2006-07-02 08:09:04.423
Date.prototype.format = function (fmt) {
    var o = {
        "M+": this.getMonth() + 1,                 //月份
        "d+": this.getDate(),                    //日
        "H+": this.getHours(),                   //小时
        "m+": this.getMinutes(),                 //分
        "s+": this.getSeconds(),                 //秒
        "q+": Math.floor((this.getMonth() + 3) / 3), //季度
        "S": this.getMilliseconds()             //毫秒
    };
    if (/(y+)/.test(fmt))
        fmt = fmt.replace(RegExp.$1, (this.getFullYear() + "").substr(4 - RegExp.$1.length));
    for (var k in o)
        if (new RegExp("(" + k + ")").test(fmt))
            fmt = fmt.replace(RegExp.$1, (RegExp.$1.length == 1) ? (o[k]) : (("00" + o[k]).substr(("" + o[k]).length)));
    return fmt;
};
//Not Supported for the first day of month ,also the last of month;
Date.prototype.addDay = function (dayNum) {
    this.setDate(this.getDate() + dayNum);
    return this;
};
Date.prototype.addSec = function (secNum) {
    this.setTime(this.getTime() + secNum);
    return this;
};
Number.prototype.add = function (arg) {
    var r1, r2, m;
    try {
        r1 = this.toString().split(".")[1].length;
    } catch (e) {
        r1 = 0;
    }
    try {
        r2 = arg.toString().split(".")[1].length;
    } catch (e) {
        r2 = 0;
    }
    m = Math.pow(10, Math.max(r1, r2));
    return (this * m + arg * m) / m;
};